<template>
	<view class="analysis-list-container">
		<!-- 头部筛选 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view class="filter-tab" 
					  :class="{ active: selectedStatus === 'all' }"
					  @click="filterByStatus('all')">
					全部
				</view>
				<view class="filter-tab" 
					  :class="{ active: selectedStatus === 'COMPLETED' }"
					  @click="filterByStatus('COMPLETED')">
					已完成
				</view>
				<view class="filter-tab" 
					  :class="{ active: selectedStatus === 'ANALYZING' }"
					  @click="filterByStatus('ANALYZING')">
					分析中
				</view>
			</view>
		</view>

		<!-- 分析结果列表 -->
		<view class="results-list">
			<view class="result-card" 
				  v-for="result in filteredResults" 
				  :key="result.id"
				  @click="viewResultDetail(result)">
				
				<view class="card-header">
					<view class="sport-info">
						<uni-icons type="videocam" size="20" color="#667eea"></uni-icons>
						<text class="sport-type">{{ getSportTypeName(result.sportType) }}</text>
					</view>
					<view class="status-badge" :class="getStatusClass(result.status)">
						<text class="status-text">{{ getStatusText(result.status) }}</text>
					</view>
				</view>

				<view class="card-content">
					<text class="video-name">{{ result.videoFileName }}</text>
					<text class="create-time">{{ formatTime(result.createTime) }}</text>
					
					<!-- 只有完成的才显示摘要 -->
					<text class="summary" v-if="result.status === 'COMPLETED' && result.summary">
						{{ result.summary }}
					</text>
					
					<!-- 分析中显示进度提示 -->
					<view class="analyzing-tip" v-if="result.status === 'ANALYZING'">
						<uni-icons type="spinner-cycle" size="16" color="#1890ff"></uni-icons>
						<text class="analyzing-text">AI正在分析您的运动视频...</text>
					</view>
					
					<!-- 失败显示错误信息 -->
					<text class="error-message" v-if="result.status === 'FAILED' && result.errorMessage">
						{{ result.errorMessage }}
					</text>
				</view>

				<view class="card-footer" v-if="result.status === 'COMPLETED'">
					<view class="action-buttons">
						<view class="action-btn primary" @click.stop="viewDetailedAnalysis(result)">
							<uni-icons type="bars" size="16" color="#fff"></uni-icons>
							<text class="btn-text">详细分析</text>
						</view>
						<view class="action-btn secondary" @click.stop="startAIGuidance(result)">
							<uni-icons type="chat" size="16" color="#667eea"></uni-icons>
							<text class="btn-text">AI指导</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="filteredResults.length === 0">
			<uni-icons type="info" size="64" color="#ccc"></uni-icons>
			<text class="empty-title">暂无分析记录</text>
			<text class="empty-subtitle">上传运动视频开始您的AI分析之旅</text>
			<button class="upload-btn" @click="goToUpload">上传视频</button>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && filteredResults.length > 0">
			<button class="load-more-btn" @click="loadMore" :disabled="loading">
				{{ loading ? '加载中...' : '加载更多' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getAnalysisResultsByUserId } from '@/api/modules/userAnalysisResult.js'
import { createConversation } from '@/api/modules/AiGuidance.js'

const analysisList = ref([])
const selectedStatus = ref('all')
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)

// 运动类型映射
const sportTypeMap = {
	'general': '通用运动',
	'running': '跑步',
	'basketball': '篮球',
	'tennis': '网球',
	'swimming': '游泳',
	'fitness': '健身'
}

// 过滤后的结果
const filteredResults = computed(() => {
	if (selectedStatus.value === 'all') {
		return analysisList.value
	}
	return analysisList.value.filter(item => item.status === selectedStatus.value)
})

onMounted(() => {
	loadAnalysisList()
})

// 加载分析列表
const loadAnalysisList = async () => {
	try {
		loading.value = true
		const userId = getCurrentUserId()
		
		if (!userId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}

		const response = await getAnalysisResultsByUserId(userId)
		if (response) {
			// 根据你提供的响应数据格式，数据在response中或response.data中
			if (Array.isArray(response)) {
				analysisList.value = response
			} else if (response.data && Array.isArray(response.data)) {
				analysisList.value = response.data
			} else if (response.length > 0) {
				analysisList.value = response
			}
		}
	} catch (error) {
		console.error('加载分析列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 按状态筛选
const filterByStatus = (status) => {
	selectedStatus.value = status
}

// 查看结果详情
const viewResultDetail = (result) => {
	if (result.status === 'COMPLETED') {
		// 跳转到详细分析页面
		uni.navigateTo({
			url: `/pages/analysis/detail?resultId=${result.resultId}&id=${result.id}`
		})
	} else if (result.status === 'ANALYZING') {
		uni.showToast({
			title: '分析进行中，请稍后查看',
			icon: 'none'
		})
	} else {
		uni.showToast({
			title: '分析失败，请重新上传',
			icon: 'none'
		})
	}
}

// 查看详细分析
const viewDetailedAnalysis = (result) => {
	uni.navigateTo({
		url: `/pages/analysis/detail?resultId=${result.resultId}&id=${result.id}`
	})
}

// 开始AI指导
const startAIGuidance = async (result) => {
	try {
		uni.showLoading({
			title: '创建AI指导会话...'
		})

		const userId = getCurrentUserId()
		const response = await createConversation({
			resultId: result.resultId,
			sportType: result.sportType,
			userId: userId
		})

		uni.hideLoading()
		uni.showToast({
			title: '已创建AI指导会话',
			icon: 'success'
		})

		// TODO: 跳转到AI对话页面
		// uni.navigateTo({
		//   url: `/pages/chat/conversation?conversationId=${response.conversationId}`
		// })

	} catch (error) {
		uni.hideLoading()
		console.error('创建AI指导会话失败:', error)
		uni.showToast({
			title: '创建会话失败',
			icon: 'none'
		})
	}
}

// 跳转到上传页面
const goToUpload = () => {
	uni.switchTab({
		url: '/pages/sth/sth'
	})
}

// 加载更多
const loadMore = async () => {
	// TODO: 实现分页加载
	uni.showToast({
		title: '暂无更多数据',
		icon: 'none'
	})
}

// 获取当前用户ID
const getCurrentUserId = () => {
	try {
		const userInfo = uni.getStorageSync('userInfo')
		if (userInfo && userInfo.id) {
			return typeof userInfo.id === 'string' ? parseInt(userInfo.id) : userInfo.id
		}
		return null
	} catch (error) {
		console.error('获取用户ID失败:', error)
		return null
	}
}

// 工具函数
const getSportTypeName = (type) => {
	return sportTypeMap[type] || type
}

const getStatusClass = (status) => {
	switch (status) {
		case 'COMPLETED': return 'status-completed'
		case 'ANALYZING': return 'status-analyzing'
		case 'FAILED': return 'status-failed'
		default: return 'status-pending'
	}
}

const getStatusText = (status) => {
	switch (status) {
		case 'COMPLETED': return '已完成'
		case 'ANALYZING': return '分析中'
		case 'FAILED': return '分析失败'
		default: return '等待中'
	}
}

const formatTime = (timeStr) => {
	const date = new Date(timeStr)
	return date.toLocaleString('zh-CN', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit'
	})
}
</script>

<style lang="scss" scoped>
.analysis-list-container {
	background-color: #f8f9fa;
	min-height: 100vh;
}

.filter-section {
	background: white;
	padding: 15px 20px;
	border-bottom: 1px solid #f0f0f0;
	
	.filter-tabs {
		display: flex;
		gap: 20px;
		
		.filter-tab {
			padding: 8px 16px;
			border-radius: 20px;
			font-size: 14px;
			color: #666;
			background-color: #f5f5f5;
			transition: all 0.3s;
			
			&.active {
				background-color: #667eea;
				color: white;
			}
		}
	}
}

.results-list {
	padding: 15px;
	
	.result-card {
		background: white;
		border-radius: 12px;
		padding: 16px;
		margin-bottom: 12px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
		
		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12px;
			
			.sport-info {
				display: flex;
				align-items: center;
				gap: 8px;
				
				.sport-type {
					font-size: 16px;
					font-weight: bold;
					color: #333;
				}
			}
			
			.status-badge {
				padding: 4px 12px;
				border-radius: 12px;
				
				.status-text {
					font-size: 12px;
					font-weight: 500;
				}
				
				&.status-completed {
					background-color: #e8f5e8;
					.status-text { color: #52c41a; }
				}
				
				&.status-analyzing {
					background-color: #e6f7ff;
					.status-text { color: #1890ff; }
				}
				
				&.status-failed {
					background-color: #fff2f0;
					.status-text { color: #ff4d4f; }
				}
			}
		}
		
		.card-content {
			margin-bottom: 12px;
			
			.video-name {
				font-size: 15px;
				color: #333;
				display: block;
				margin-bottom: 6px;
			}
			
			.create-time {
				font-size: 13px;
				color: #999;
				display: block;
				margin-bottom: 8px;
			}
			
			.summary {
				font-size: 14px;
				color: #666;
				line-height: 1.5;
				display: block;
				margin-bottom: 8px;
			}
			
			.analyzing-tip {
				display: flex;
				align-items: center;
				gap: 6px;
				padding: 8px 12px;
				background-color: #e6f7ff;
				border-radius: 6px;
				
				.analyzing-text {
					font-size: 13px;
					color: #1890ff;
				}
			}
			
			.error-message {
				font-size: 13px;
				color: #ff4d4f;
				background-color: #fff2f0;
				padding: 8px 12px;
				border-radius: 6px;
				display: block;
			}
		}
		
		.card-footer {
			border-top: 1px solid #f0f0f0;
			padding-top: 12px;
			
			.action-buttons {
				display: flex;
				gap: 10px;
				
				.action-btn {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 6px;
					padding: 10px;
					border-radius: 6px;
					font-size: 14px;
					
					&.primary {
						background-color: #667eea;
						.btn-text { color: white; }
					}
					
					&.secondary {
						background-color: #f5f5f5;
						.btn-text { color: #667eea; }
					}
				}
			}
		}
	}
}

.empty-state {
	text-align: center;
	padding: 60px 20px;
	
	.empty-title {
		font-size: 18px;
		color: #333;
		display: block;
		margin: 16px 0 8px 0;
	}
	
	.empty-subtitle {
		font-size: 14px;
		color: #666;
		display: block;
		margin-bottom: 24px;
	}
	
	.upload-btn {
		background-color: #667eea;
		color: white;
		border: none;
		border-radius: 20px;
		padding: 10px 24px;
		font-size: 14px;
	}
}

.load-more {
	padding: 20px;
	text-align: center;
	
	.load-more-btn {
		background-color: #f5f5f5;
		color: #666;
		border: none;
		border-radius: 20px;
		padding: 10px 24px;
		font-size: 14px;
		
		&:disabled {
			opacity: 0.6;
		}
	}
}
</style> 